﻿using BarcodeDelay.bean;
using BarcodeDelay.logHelp;
using BarcodeDelay.utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class ProblemReturnHelperGen
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListCancelsBarcodes = new ArrayList();
        public event Action CancelsEvent;

        private static ProblemReturnHelperGen instance;
        public static ProblemReturnHelperGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ProblemReturnHelperGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes)
        {
            try
            {
                initLog();
                m_arListCancelsBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListCancelsBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseProblemsReturn));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;
              

            }
            catch (Exception ex)
            {

            }
        }



        public void parseProblemsReturn(object arListBarcodes)
        {
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                JArray wayBills = new JArray();
                string lastBarcode = "";
                Hashtable htCustomer = new Hashtable();
                string roomID = "";
                string fromID = "";
                foreach (ParcelBean parcelBean in (ArrayList)arListBarcodes)
                {
                    string strBarCode = parcelBean.wayBill;
                    fromID = parcelBean.fromWxID;
                    wayBills.Add(strBarCode.Trim());
                    lastBarcode = strBarCode.Trim();
                    roomID = parcelBean.roomID;
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    string customerName = "";
                    if (!UtilityHelp.Instance.resetToken(strBarCode.Trim(),out pickName,out orderSource,out curSiteToken,out customerName))
                    {
                        if (curSiteToken == "")
                        {
                            StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 登录失效";
                            continue;
                        }
                        StoParams.Instance.htResWechat[lastBarcode] = " 发件网点 "+ pickName+ " 非我司单号  无法处理";
                        return;
                    }
                    
                    parcelBean.customerName = customerName;
                    parcelBean.rebackTransferReason = UtilityHelp.Instance.getReturnReason(parcelBean.wayBill.ToString(), pickName);
                    if(!htCustomer.ContainsKey(customerName))
                    {
                        htCustomer[customerName] = new ArrayList();
                    }
                    ArrayList arListProblems = htCustomer[customerName] as ArrayList;
                    arListProblems.Add(parcelBean);
                    //StoParams.Instance.htResWechat[strBarCode] = "退回审核问题件汇总";


                    //StoParams.Instance.htResWechat[lastBarcode] = resMsg;

                }
                ArrayList arListAll = new ArrayList();
                foreach (DictionaryEntry de in htCustomer)
                {
                    ArrayList arListCustomers = (ArrayList)de.Value;
                    ParcelBean firstParcel = (ParcelBean)arListCustomers[0];
                    arListAll.AddRange(arListCustomers);
                    //sendCustomerProblemNotice(firstParcel.customerName, arListCustomers, firstParcel.roomID);
                }
                string sPath = "";
                bool result = UtilityExcel.Instance.GenExcelForProblemReturn(arListAll, StoParams.Instance.outputDir, out sPath);
                
                string response = "";
                if (result)
                {
                    logHelp.LogHelper.Instance.writeLog("生成退转问题件统计报表成功");

                    string outputPath = UtilityHelp.Instance.uploadToAliyun(sPath, roomID);
                    response = "{$@}" + " 生成退转问题件统计报表成功\r\n" + outputPath;

                }
                else
                {
                    logHelp.LogHelper.Instance.writeLog("生成统计报表失败");
                    response = "{$@}" + "生成留言板报表失败";
                }
                ReplyHelper.Instance.replySuperMsg(roomID, response, "1", fromID);





            }
            catch (Exception ex)
            {
                

            }
            int tiot = queryServerResTime;
           


        }

        private void sendCustomerProblemNotice(string customerName, ArrayList arListParcel, string roomID)
        {
            try
            {
                
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(customerName);
                foreach (ParcelBean parcel in arListParcel)
                {                    
                    sb.AppendLine(parcel.wayBill + " " + parcel.rebackTransferReason);
                }
                ReplyHelper.Instance.replySuperMsg(roomID, sb.ToString());
                LogHelper.Instance.writeLog("发送问题件通知：" + customerName);
  
            }
            catch (Exception ex)
            {

            }
        }




        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
